<template>
  <div class="drafts">
    <div class="filter-bar-wrapper">
      <FilterBar
        :searchQuery="searchQuery"
        showSearch
        @update:searchQuery="searchQuery = $event"
      />
    </div>

    <LoadingWrapper :loading="loading">
      <div>
        <el-tabs v-model="activeTab">
          <el-tab-pane label="全部" name="all">
            <el-table 
              v-if="draftsList.length > 0"
              :data="paginatedDrafts"
              style="width: 100%" 
              :cell-style="{ padding: '12px 0' }"
            >
              <el-table-column 
                label="序号" 
                width="80"
                align="center"
                header-align="center"
              >
                <template #default="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              
              <el-table-column 
                prop="title" 
                label="书名" 
                min-width="180"
                show-overflow-tooltip
                align="center"
                header-align="center"
              >
                <template #default="scope">
                  {{ scope.row.title }} [草稿]
                </template>
              </el-table-column>
              
              <el-table-column 
                prop="author" 
                label="作者" 
                min-width="120"
                show-overflow-tooltip
                align="center"
                header-align="center"
              />
              
              <el-table-column 
                prop="tags" 
                label="标签" 
                min-width="150"
                align="center"
                header-align="center"
              >
                <template #default="scope">
                  <el-tag
                    v-for="tag in (scope.row.tags ? scope.row.tags.split(/\s+/).filter(tag => tag) : [])"
                    :key="tag"
                    size="small"
                    class="mx-1"
                  >
                    {{ tag }}
                  </el-tag>
                </template>
              </el-table-column>
              
              <el-table-column 
                prop="updated_at" 
                label="最后保存时间" 
                width="180"
                align="center"
                header-align="center"
              />

              <el-table-column 
                label="操作" 
                width="200"
                fixed="right"
                align="center"
              >
                <template #default="{ row }">
                  <div class="operation-cell">
                    <el-tooltip content="编辑" placement="top">
                      <el-button type="primary" link @click="handleEdit(row)">
                        <el-icon><Edit /></el-icon>
                      </el-button>
                    </el-tooltip>

                    <el-tooltip content="发布" placement="top">
                      <el-button 
                        type="success" 
                        link 
                        @click="handlePublish(row.id)"
                      >
                        <el-icon><Upload /></el-icon>
                      </el-button>
                    </el-tooltip>

                    <el-tooltip content="删除" placement="top">
                      <el-button 
                        type="danger" 
                        link 
                        @click="handleDelete(row.id)"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无草稿数据" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </LoadingWrapper>

    <div class="pagination-wrapper">
      <PaginationBar
        v-if="filteredDrafts.length > 0"
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :total="filteredDrafts.length"
        :pageSizes="[10, 15, 20, 25]"
        @pagination-change="handlePaginationChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Edit,
  Delete,
  Upload
} from '@element-plus/icons-vue'
import { getDrafts, deleteDraft, publishDraft } from '@/api/draft'
import { formatDateTime } from '@/utils/format'
import FilterBar from '@/components/filter/FilterBar.vue'
import PaginationBar from '@/components/pagination/PaginationBar.vue'
import LoadingWrapper from '@/components/loading/LoadingWrapper.vue'

const router = useRouter()
const draftsList = ref([])
const activeTab = ref('all')

// 搜索相关
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 过滤草稿列表
const filteredDrafts = computed(() => {
  return draftsList.value.filter(draft => {
    const matchQuery = !searchQuery.value || 
      draft.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      draft.author.toLowerCase().includes(searchQuery.value.toLowerCase())
    return matchQuery
  })
})

// 分页后的草稿列表
const paginatedDrafts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredDrafts.value.slice(start, end)
})

// 处理分页变化
const handlePaginationChange = ({ type, value }) => {
  if (type === 'page') {
    currentPage.value = value
  } else if (type === 'size') {
    pageSize.value = value
    currentPage.value = 1  // 重置到第一页
  }
}

// 监听筛选条件变化，重置页码
watch(searchQuery, () => {
  currentPage.value = 1
})

// 添加 loading 状态
const loading = ref(true)

// 获取草稿列表
const loadDraftList = async () => {
  try {
    loading.value = true
    const response = await getDrafts()
    if (response.code === 200) {
      draftsList.value = response.data.map(draft => ({
        ...draft,
        updated_at: formatDateTime(draft.updated_at)
      }))
    }
  } catch (error) {
    console.error('获取草稿列表失败:', error)
    ElMessage.error('获取草稿列表失败')
  } finally {
    loading.value = false
  }
}

// 编辑草稿
const handleEdit = (draft) => {
  // 在新标签页打开编辑页面
  const routeUrl = router.resolve({
    name: 'DraftEdit',
    params: { id: draft.id }
  })
  window.open(routeUrl.href, '_blank')
}

// 发布草稿
const handlePublish = async (draftId) => {
  try {
    await ElMessageBox.confirm('确定要发布这篇草稿吗？发布后将不能再编辑', '提示', {
      confirmButtonText: '确定发布',
      cancelButtonText: '取消',
      type: 'info'
    })

    const response = await publishDraft(draftId)
    if (response.code === 200) {
      ElMessage.success('发布成功')
      loadDraftList()   
    } else {
      ElMessage.error(response.message || '发布失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '发布失败')
    }
  }
}

// 删除草稿
const handleDelete = async (draftId) => {
  try {
    await deleteDraft(draftId)
    ElMessage.success('删除成功')
    loadDraftList()
  } catch (error) {
    ElMessage.error(error.message || '删除失败')
  }
}

// 初始加载
onMounted(() => {
  loadDraftList()
})
</script>

<style scoped>
.drafts {
  padding: 20px;
}

.filter-bar-wrapper {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-tag) {
  margin: 0 4px;
}

.el-icon {
  font-size: 18px;
}

.operation-cell {
  display: flex;
  justify-content: center;
  gap: 6px;

  :deep(.el-button) {
    padding: 0;
  }
}

:deep(.el-table) {
  margin-bottom: 20px;
}
</style>